#This script plots the DSL coefficients for Tunisia and Egypt
#It produces Figure K1 in the paper  
library(ggplot2)
library(dplyr)
library(ggthemes)
library(zoo)
library(cowplot)

all_data <- readRDS("data/output/cos_sims_dsl/mastun_estimation_data_yearmon.rds")
all_data$group <- 1
all_data$country_name[all_data$country_name=="masress"] <- "Egypt"
all_data$country_name[all_data$country_name=="turess"] <- "Tunisia"

# Convert yearmon to Date class
all_data$yearmon <- as.Date(as.yearmon(all_data$yearmon, "%Y-%m"))

g1 <- all_data %>%
  ggplot(aes(x = yearmon, y = coefficient, group = group)) +
  geom_point(alpha = .25) +
  geom_line(alpha = .25) +
  geom_smooth(
    method = "loess",
    size = 1,
    span = .5,
    fill = "white",
    col = "black",
  ) +
  theme_tufte(base_family = "Helvetica") +
  labs(x = "Year-month",
       y = "DSL coefficient") + 
  ylim(-1, 5) +
  scale_x_date(date_breaks = "1 year", date_labels = "%Y", minor_breaks = "1 month") +
  theme(
    legend.position = "right",
    axis.text.x = element_text(size = 20),
    axis.text.y = element_text(size = 20),
    axis.title.x = element_text(size = 15),
    axis.title.y = element_text(size = 15),
    legend.text = element_text(size = 15),
    legend.title = element_text(size = 20),
    panel.border = element_rect(
      colour = "black",
      fill = NA,
      linewidth  = 1
    ),
    plot.background = element_rect(fill = "white", colour = NA),
    strip.text = element_text(size = 20)
  ) +
  facet_wrap(~ country_name, ncol = 2)


all_data <- readRDS("data/output/cos_sims_dsl/mastun_estimation_data_year.rds")
all_data$group <- 1
all_data$country_name[all_data$country_name=="masress"] <- "Egypt"
all_data$country_name[all_data$country_name=="turess"] <- "Tunisia"

g2 <- all_data %>%
  ggplot(aes(x = year, y = coefficient, group = group)) +
  geom_point(alpha = .25) +
  geom_line(alpha = .25) +
  geom_smooth(
    method = "loess",
    size = 1,
    span = .5,
    fill = "white",
    col = "black",
  ) +
  theme_tufte(base_family = "Helvetica") +
  labs(x = "Year",
       y = "DSL coefficient") + 
  theme(
    legend.position = "right",
    axis.text.x = element_text(size = 20),
    axis.text.y = element_text(size = 20),
    axis.title.x = element_text(size = 15),
    axis.title.y = element_text(size = 15),
    legend.text = element_text(size = 15),
    legend.title = element_text(size = 20),
    panel.border = element_rect(
      colour = "black",
      fill = NA,
      linewidth  = 1
    ),
    plot.background = element_rect(fill = "white", colour = NA),
    strip.text = element_text(size = 20)
  ) +
  facet_wrap(~ country_name, ncol = 2)



png(
  "plots/figK1.png",
  width = 500,
  height = 300,
  units = 'mm',
  res = 300
)
plot_grid(g1,g2, nrow = 2,
          labels = "AUTO")
dev.off()